#include <vtkSmartPointer.h>
#include <vtkAutoInit.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkPoints.h>
#include <vtkDelaunay2D.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkSurfaceReconstructionFilter.h>
#include <vtkMarchingCubes.h>



VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);


int main(int argc, char *argv[])
{
  vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
  unsigned int n = 10;
  for (unsigned int i = 0; i < n; i++)
  {
    for (size_t j = 0; j < n ; j++) {    
        points->InsertNextPoint(i,j, vtkMath::Random(0.0, 1.0));
    }
  }
  vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
  polydata->SetPoints(points);

  vtkSmartPointer<vtkSurfaceReconstructionFilter> surface = vtkSmartPointer<vtkSurfaceReconstructionFilter>::New();
  surface->SetInputData(polydata);
  surface->SetSampleSpacing(1);
  surface->SetNeighborhoodSize(5);
  surface->Update();

//   vtkSmartPointer<vtkDelaunay2D> delaunay = vtkSmartPointer<vtkDelaunay2D>::New();
//   delaunay->SetInputData(polydata);
//   delaunay->Update();
  //展示对应的三角格网
//   vtkSmartPointer<vtkPolyData> output = delaunay->GetOutput();
//   vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
//   mapper->SetInputData(output);
//   vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
//   actor->SetMapper(mapper);
//   vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
//   renderer->AddActor(actor);
  //展示surface重建后的数据

  // 使用 Marching Cubes 提取等值面
  vtkSmartPointer<vtkMarchingCubes> isoSurface = vtkSmartPointer<vtkMarchingCubes>::New();
  isoSurface->SetInputConnection(surface->GetOutputPort());
  isoSurface->SetValue(0, 0.0);  // 设置等值面阈值
  isoSurface->Update();

  // 显示重建后的表面
  vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(isoSurface->GetOutputPort());

  vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
  actor->SetMapper(mapper);
 
  vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
  renderer->AddActor(actor);

  vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
  renderWindow->AddRenderer(renderer);
  vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(renderWindow);
  renderWindowInteractor->Initialize();
  renderWindowInteractor->Start();
  vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
  renderWindowInteractor->SetInteractorStyle(style);
  return EXIT_SUCCESS;
 
}